package com.leetcode;

/**
 * 283. 移动零
 *
 * @author fy
 * @date 2022/4/1 20:25
 */
public class Solution283 {

    public void moveZeroes(int[] nums) {
        for (int i = 0, j = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                if (i != j) {
                    nums[j++] = nums[i];
                    nums[i] = 0;
                } else {
                    j++;
                }
            }
        }
    }

    public void moveZeroes11(int[] nums) {
        if (nums == null || nums.length <= 1) {
            return;
        }
        int j = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                nums[j++] = nums[i];
            }
        }
        while (j < nums.length) {
            nums[j++] = 0;
        }
    }

    public void moveZeroes1(int[] nums) {
        if (nums == null || nums.length <= 1) {
            return;
        }
        int realIndex = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0 && realIndex != i) {
                nums[realIndex++] = nums[i];
            } else if (nums[i] != 0) {
                realIndex++;
            }
        }
        while (realIndex < nums.length) {
            nums[realIndex++] = 0;
        }
    }

    public void moveZeroes2(int[] nums) {
        if (nums == null || nums.length <= 1) {
            return;
        }
        int n = nums.length;
        int[] newNums = new int[n];
        int j = 0;
        for (int num : nums) {
            if (num != 0) {
                newNums[j++] = num;
            }
        }
        while (j < n) {
            nums[j++] = 0;
        }
        nums = newNums;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{0, 23, 300, 293, 0, 32, 30, 0};
//        int[] nums = new int[]{0, 1, 0, 3, 12};
        new Solution283().moveZeroes(nums);
        for (int i = 0; i < nums.length; i++) {
            System.out.print(nums[i] + " ");
        }

    }
}
